﻿using System;
using System.Linq;
using System.Linq.Expressions;
using SBACN.WebSite.Cache;
using SBACN.WebSite.Code;
using SBACN.WebSite.Models;

namespace SBACN.WebSite.Admin.AboutGuild
{
	public partial class CMRaletionAdd : BasePage
	{

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!AdminBasePage.CheckCodeRight(AdminBasePage.AdminInfo, this.SystemCode))
			{
				AdminBasePage.RedirectWithMessage(AdminDefaultPage, "您没有访问当前页面的权限,请与系统管理员联系!");
				return;
			}

			if (!IsPostBack)
			{
				this.HidCID.Value = Request.QueryString["id"];
				DropDownListMember();
				DropDownListMClass();
			}
		}

		protected void DropDownListMClass()
		{
			var result = SystemMapCache.Instance.List.Where(c => c.Code.StartsWith("000100050")).ToList();
			this.MClass.AppendDataBoundItems = true;
			this.MClass.DataSource = result;
			this.MClass.DataTextField = "CText";
			this.MClass.DataValueField = "Code";
			this.MClass.DataBind();
		}

		protected void DropDownListMember()
		{
			int id = 0;
			if (Int32.TryParse(Request.QueryString["id"], out id))
			{
				Expression<Func<View_CinfoRelationMember, bool>> F = (p => p.Index == id);
				var resultCR = DAL.DALHelper.Instance.GetList<View_CinfoRelationMember>(F).Select(c => (new { id = c.MID, name = c.MName }));

				Expression<Func<TB_Member, bool>> f1 = (p => true);
				var resultM = DAL.DALHelper.Instance.GetList<TB_Member>(f1).Select(c => (new { id = c.ID, name = c.Name }));

				var expectedList = resultM.Except(resultCR);

				this.Member.AppendDataBoundItems = true;
				this.Member.DataSource = expectedList;
				this.Member.DataTextField = "name";
				this.Member.DataValueField = "id";
				this.Member.DataBind();
			}
		}

		protected void SubBtn_Click( object sender, EventArgs e)
		{
			int cid = 0;
			if (Int32.TryParse(this.HidCID.Value, out cid))
			{
				var result = DAL.DALHelper.Instance.Create<TB_CouncilRelation>();
				result.MemberID = Convert.ToInt32(this.Member.SelectedValue);
				result.Type = this.MClass.SelectedValue;
				result.Index = cid;
				DAL.DALHelper.Instance.Add<TB_CouncilRelation>(result);
				DAL.DALHelper.Instance.SaveChanges();

				BasePage.CloseWindow(true);
			}
			else
			{
				ClientScript.RegisterClientScriptBlock(this.GetType(),"AlertMsg","<script type='text/javascript'>alert('页面加载错误！请注销重新登入后再操作。');window.close();</script>");
				return;
			}
		}

	}
}